package com.hujie.sqlqueryes.service.sql;

import com.hujie.sqlqueryes.dto.DslResultDTO;
import com.hujie.sqlqueryes.service.impl.QueryExpressionBuilderImpl;
import com.hujie.sqlqueryes.service.util.JsonEscapeUtil;
import com.hujie.sqlqueryes.service.util.SqlExpressionUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * SELECT语句处理器
 */
@Component
public class SelectStatementHandler implements SqlStatementHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(SelectStatementHandler.class);
    
    @Autowired
    private QueryExpressionBuilderImpl queryExpressionBuilder;
    
    @Override
    public boolean supports(Statement statement) {
        return statement instanceof Select;
    }
    
    @Override
    public DslResultDTO handle(Statement statement) {
        try {
            Select selectStatement = (Select) statement;
            String dsl = buildDslFromSelect(selectStatement);
            logger.info("SELECT语句转换完成");
            logger.debug("生成的DSL: {}", dsl);
            return DslResultDTO.success(dsl);
        } catch (Exception e) {
            logger.error("SELECT语句转换失败: {}", e.getMessage(), e);
            return DslResultDTO.error("SELECT语句转换失败: " + e.getMessage());
        }
    }
    
    private String buildDslFromSelect(Select selectStatement) {
        // 修复SelectBody类型问题
        Object selectBody = selectStatement.getSelectBody();
        if (!(selectBody instanceof PlainSelect)) {
            return "{\n  \"query\": {\n    \"match_all\": {}\n  }\n}";
        }
        
        PlainSelect plainSelect = (PlainSelect) selectBody;
        StringBuilder dsl = new StringBuilder();
        dsl.append("{\n");
        
        // 获取表名（索引名）
        String tableName = null;
        if (plainSelect.getFromItem() instanceof Table) {
            Table table = (Table) plainSelect.getFromItem();
            tableName = table.getName();
            // 处理包含特殊字符的索引名称（去除方括号）
            if (tableName != null && tableName.startsWith("[") && tableName.endsWith("]")) {
                tableName = tableName.substring(1, tableName.length() - 1);
            }
        }
        
        // 添加索引名到DSL中
        if (tableName != null) {
            dsl.append("  \"index\": \"").append(tableName).append("\",\n");
        }
        
        // 处理WHERE条件
        Expression where = plainSelect.getWhere();
        if (where != null) {
            dsl.append("  \"query\": ").append(queryExpressionBuilder.buildQueryFromExpression(where)).append(",\n");
        } else {
            dsl.append("  \"query\": {\n    \"match_all\": {}\n  },\n");
        }
        
        // 处理LIMIT
        Limit limit = plainSelect.getLimit();
        if (limit != null) {
            // 修复rowCount()方法调用，现在返回的是Expression类型
            Expression rowCountExpression = limit.getRowCount();
            if (rowCountExpression instanceof LongValue) {
                long limitValue = ((LongValue) rowCountExpression).getValue();
                dsl.append("  \"size\": ").append(limitValue).append(",\n");
            }
        }
        
        // 处理OFFSET
        Offset offset = plainSelect.getOffset();
        if (offset != null) {
            // 修复getOffset()方法调用
            Expression offsetExpression = offset.getOffset();
            if (offsetExpression instanceof LongValue) {
                long offsetValue = ((LongValue) offsetExpression).getValue();
                dsl.append("  \"from\": ").append(offsetValue).append(",\n");
            }
        }
        
        // 删除最后的逗号
        if (dsl.charAt(dsl.length() - 2) == ',') {
            dsl.deleteCharAt(dsl.length() - 2);
        }
        
        dsl.append("}");
        return dsl.toString();
    }
}